package com.charging.business.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.charging.business.config.MinFeeManager;
import com.charging.business.domain.FeeEntryInfoModel;
import com.charging.business.utils.DateEx;
import com.charging.business.utils.VehicleClassUtil;
import com.charging.business.vo.FeeEnCalcRequest;
import com.charging.business.vo.FeeEnCalcResponse;
import com.charging.business.enums.Free;
import com.charging.business.exception.CustomizeException;
import com.charging.business.gantry.EntryFeeCalcResponse;
import com.charging.business.gantry.GantryCalcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author JerryLu
 * @date 2024/8/26 16:16
 * @description 入口计费ETC计算方法
 */
@Component
public class FeeInEtcHandle {
    private static final Logger logger = LoggerFactory.getLogger(FeeInMtcHandle.class);
    /**
     * 入口车型
     */
    public int enVehicleType = 0;
    /**
     * 入口轴数
     */
    public int enAxleCount = 0;
    /**
     * 入口计费车型
     */
    public int enFeeVehicleType = 0;
    /**
     * 入口计费轴数
     */
    public int enFeeAxleCount = 0;
    /**
     * 入口车种
     */
    public int enVehicleClass = 0;
    /**
     * 特殊车辆标识<p>
     * Ox00 -本次通行用于ETC大件运输
     * Ox01 -非优惠车辆
     * Ox02 -绿通车辆
     * Ox03 -联合收割机车辆
     * Ox04 -集装箱车辆
     * Ox05-0xFE -保留 注：可选填
     * 默认写入 OxFF
     */
    public int enVehicleSign = 255;
    /**
     * 入口车牌(含颜色)
     */
    public String enVehicleId = "";
    /**
     * 用户卡发行方
     */
    public String issuerId = "";
    /**
     * 入口时间
     */
    public DateEx enTime = DateEx.make(0);
    @Autowired
    private MinFeeManager minFeeManager;
    @Autowired
    private GantryCalcUtils gantryCalcUtils;
    private final Free free; //免费信息

    @Autowired
    public FeeInEtcHandle(Free free) {
        this.free = free;
    }

    /**
     * TODO
     *
     * @param content
     * @param response
     * @return void
     * @author JerryLu
     * @date 2024/8/26 18:45
     */
    public FeeEnCalcResponse run(FeeEnCalcRequest content, FeeEnCalcResponse response) throws CustomizeException {
        if (content.getEnTollStationHex().length() != 8) {
            throw new CustomizeException("入口站Hex码格式错误");
        }
        enTime = DateEx.make(content.getCurPassTime(), "yyyy-MM-dd'T'HH:mm:ss");

        enVehicleId = content.getVehicleId().toUpperCase().replaceAll("\\.", ""); //入口车牌处理
        enVehicleType = content.getEnVehicleType();//入口车型
        enAxleCount = content.getEnAxleCount();//入口轴数
        enVehicleClass = content.getVehicleClass(); //入口车种
        enVehicleSign = content.getVehicleSign(); //车辆特殊标识
        if (enVehicleType < 10) {
            enVehicleSign = 255;
        }
        issuerId = content.getIssuerId();

        // 按入口车种设置免费标识
        // 部应急保障车检查
        checkVehicleFee();

        // 确定入口收费车型
//        checkEnExVType();

        // 兜底费率版本检查
        checkMinFee();

        // 按入口信息(标签信息)计费
        response = this.libraryFee(content, response);

        return response;
    }

    public void checkVehicleFee() {
        //军车及应急救援
        if (enVehicleClass == VehicleClassUtil.AP && VehicleClassUtil.isArmyETC(issuerId)) {// 军车
            free.set(Free.ARMY);
        } else if (enVehicleClass == VehicleClassUtil.ETC_EMER) {// 应急救援
            free.set(Free.ERES);
        } else if (enVehicleId.contains("警") && enVehicleId.contains("晋")) {// 本省警车,注意：为入口车牌
            free.set(Free.POLIC);
        } else if (enVehicleClass == VehicleClassUtil.MTC_JJC) {// 紧急车
            free.set(Free.JJ);
        } else if (enVehicleClass == VehicleClassUtil.MTC_RESCUE) {// 抢险救灾
            free.set(Free.QXJZ);
        }
    }

    public void checkEnExVType() {
        enFeeAxleCount = enAxleCount;
        enFeeVehicleType = enVehicleType;
        if (enFeeVehicleType > 10) {// 入口为货车
            if (VehicleClassUtil.isTrailer(enVehicleClass) || enVehicleSign == 0x00) {// 为J1、J2、甩挂车、大件运输车货车
                int multi = enFeeVehicleType / 10;
                if (enFeeAxleCount == 3) {
                    enFeeVehicleType = multi * 10 + 3;
                } else if (enFeeAxleCount == 4) {
                    enFeeVehicleType = multi * 10 + 4;
                } else if (enFeeAxleCount == 5) {
                    enFeeVehicleType = multi * 10 + 5;
                } else if (enFeeAxleCount >= 6) {
                    enFeeVehicleType = multi * 10 + 6;
                }

                // ETC才有的情况
                if (enFeeVehicleType < enVehicleType) {
                    enFeeVehicleType = enVehicleType;
                }
            } else {
                if (enFeeVehicleType == 11 || enFeeVehicleType == 21) {
                    enFeeAxleCount = 2;
                } else if (enFeeVehicleType == 12 || enFeeVehicleType == 22) {
                    enFeeAxleCount = 2;
                } else if (enFeeVehicleType == 13 || enFeeVehicleType == 23) {
                    enFeeAxleCount = 3;
                } else if (enFeeVehicleType == 14 || enFeeVehicleType == 24) {
                    enFeeAxleCount = 4;
                } else if (enFeeVehicleType == 15 || enFeeVehicleType == 25) {
                    enFeeAxleCount = 5;
                } else if (enFeeVehicleType == 16 || enFeeVehicleType == 26) {
                    enFeeAxleCount = 6;
                }
            }
        } else {
            enFeeAxleCount = 2;
        }
    }

    public void checkMinFee() throws CustomizeException {
        // 获取最小费额版本号
        String minVersion = minFeeManager.getMinFeeVersion();
//        if (minVersion.isEmpty()) throw new CustomizeException("获取兜底费率版本失败");
    }

    public FeeEnCalcResponse libraryFee(FeeEnCalcRequest content, FeeEnCalcResponse response) throws CustomizeException {
        FeeEntryInfoModel etcDto = JSONObject.parseObject(JSON.toJSONString(content), FeeEntryInfoModel.class);
        etcDto.setLaneStatus(content.laneType);
        etcDto.setEnPassTime(content.curPassTime);
        etcDto.setLastGantryHex("000000");
        etcDto.setLastPassTime(LocalDateTime.parse(content.curPassTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
        etcDto.setCardNetwork(content.CPUNetID);
        etcDto.setAxleCount(content.enAxleCount);
        etcDto.setTagType(1);
        etcDto.setCardType(content.CPUCardType);
        etcDto.setCardVer(content.CPUVersion);
        etcDto.setObuSn(content.OBUSN);
        etcDto.setCpuCardId(content.CPUCardId);
        etcDto.setPlateHex(content.vehicleId.split("_")[0]);
        etcDto.setPlateColor(Integer.valueOf(content.vehicleId.split("_")[1]));
        etcDto.setVehicleType(content.enVehicleType);
        etcDto.setVehicleWeightLimits(content.obuPermittedTowWeight);
        etcDto.setVehicleStatusFlag(content.vehicleSign);
        etcDto.setFeeProvBeginHex("");//000000
        etcDto.setFeeProvMileage(-1);
        etcDto.setFeeProvGantryNum(-1);
        etcDto.setPayFeeSumLocal(-1);
        etcDto.setRealFeeSumLocal(-1);
        etcDto.setGantryPassNum(0);
        etcDto.setGantryPassHex("");
        EntryFeeCalcResponse feeCalcResponse = gantryCalcUtils.libraryFee(etcDto);
        response = JSONObject.parseObject(JSON.toJSONString(feeCalcResponse), FeeEnCalcResponse.class);
        if (feeCalcResponse.getCode() != 0) {
            response.setCodeInfo(feeCalcResponse.getMsg());
        }

        return response;
    }
}
